﻿using System;
using System.Windows.Forms;
using DbManager;
using DbManager.DataManager;
using DbManager.QueryBuilder;
using DbManager.QueryBuilder.DbEntity.IND;

namespace TAProject.UI.Service
{
    public partial class FormName : FormTemplate
    {
        private readonly IConnectionManager _connectionManager;
        private readonly IDataManager _dataManager;
        private readonly IQueryInd _iQueryInd;

        private readonly bool _isUpdate;
        private readonly Form _parentForm;

        public FormName(Form parentForm, IDataManager dataManager, IConnectionManager connectionManager,
                        IQueryInd iQueryInd, bool isUpdate)
            : base(parentForm)
        {
            InitializeComponent();

            _parentForm = parentForm;
            _dataManager = dataManager;
            _connectionManager = connectionManager;
            _iQueryInd = iQueryInd;

            _parentForm.Enabled = false;

            _isUpdate = isUpdate;
            if (_isUpdate)
            {
                textBoxName.Text = _iQueryInd.Name;
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            FormClose();
        }

        private void buttonSubmit_Click(object sender, EventArgs e)
        {
            //MessageBox.Show(_iQueryInd.Name + " " + _iQueryInd.ForeignID + " " + _iQueryInd.ID);
            if (!string.IsNullOrEmpty(textBoxName.Text))
            {
                _iQueryInd.Name = textBoxName.Text;
                var rowAffected =
                    _dataManager.ManageDataInDb(
                        _isUpdate ? _iQueryInd.GetUpdateQuery() : _iQueryInd.GetInsertQuery(),
                        _connectionManager.GetConnection());
                if (rowAffected == 0)
                {
                    MessageBox.Show("Ошибка сохранения даных.");
                }
                else
                {
                    FormClose();
                }
            }
            else
            {
                MessageBox.Show("Поле 'Название' не заполнено.");
            }
        }

        private void FormClose()
        {
            _parentForm.Enabled = true;
            Close();
        }
    }
}